package cn.skylark.wcm.common.scheduler;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
@EnableScheduling
public class SchedulerConfig {
  @Autowired
  private SpringJobFactory springJobFactory;

  @Bean
  public SchedulerFactoryBean schedulerFactoryBean() {
    SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
    schedulerFactoryBean.setJobFactory(springJobFactory);
    return schedulerFactoryBean;
  }

  @Bean
  public Scheduler scheduler()  throws SchedulerException {
    Scheduler scheduler = schedulerFactoryBean().getScheduler();
    startJob1(scheduler);
    startJob2(scheduler);
    return scheduler;
  }

  private void startJob1(Scheduler scheduler) throws SchedulerException {
    JobDetail jobDetail =
            JobBuilder.newJob( ScheduledJob1.class).withIdentity("supersearch推送txt文件任务", "group1").build();
    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/1 * * * ?");
    CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")
            .withSchedule(scheduleBuilder).build();
    scheduler.scheduleJob(jobDetail, cronTrigger);
  }
  private void startJob2(Scheduler scheduler) throws SchedulerException {
    JobDetail jobDetail =
            JobBuilder.newJob( ScheduledJob2.class).withIdentity("清除redis服务器过期TOKEN", "group2").build();
    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 0 0/1 * * ?");
    CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger2", "group2")
            .withSchedule(scheduleBuilder).build();
    scheduler.scheduleJob(jobDetail, cronTrigger);
  }
}
